package com.saascloud.restTemplate.config;

import com.google.common.collect.Lists;
import com.saascloud.restTemplate.core.RestTemplateProperties;
import com.saascloud.restTemplate.core.SaasRequestInteceptor;
import com.saascloud.restTemplate.core.SaasRestTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

/**
 * @Author: liangxu
 * @Contact: one_dream@aliyun.com
 * @Date: 2022/5/30 15:43
 * @Version: 1.0
 * @Description:
 */
@EnableConfigurationProperties(RestTemplateProperties.class)
public class SaasRestTemplateAutoConfig {

    @Autowired
    private RestTemplateProperties restTemplateProperties;


    @Bean("restTemplate")
    public RestTemplate restTemplate() {
        HttpComponentsClientHttpRequestFactory httpRequestFactory = new HttpComponentsClientHttpRequestFactory();
        httpRequestFactory.setConnectTimeout(restTemplateProperties.getConnectTimeout());
        httpRequestFactory.setReadTimeout(restTemplateProperties.getReadTimeout());
        RestTemplate restTemplate = new RestTemplate(httpRequestFactory);
        restTemplate.setInterceptors(Lists.newArrayList(new SaasRequestInteceptor()));
        return restTemplate;
    }

    @LoadBalanced
    @Bean("lbRestTemplate")
    public RestTemplate LoadBalancedRestTemplate() {
        HttpComponentsClientHttpRequestFactory httpRequestFactory = new HttpComponentsClientHttpRequestFactory();
        httpRequestFactory.setConnectTimeout(restTemplateProperties.getConnectTimeout());
        httpRequestFactory.setReadTimeout(restTemplateProperties.getReadTimeout());
        RestTemplate restTemplate = new RestTemplate(httpRequestFactory);
        restTemplate.setInterceptors(Lists.newArrayList(new SaasRequestInteceptor()));
        return restTemplate;
    }

    @Bean
    public SaasRestTemplate saasRestTemplate() {
        return new SaasRestTemplate();
    }

}
